package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.RedisCacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@Service
public class TaskServiceImpl implements TaskService {
    @Autowired
    private RedisCacheService redisCacheService;
    @Autowired
    private TaskinfoMapper taskinfoMapper;
    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    @Autowired
    private ThreadPoolTaskExecutor threaPool;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    /**
     * 添加任务
     * @param task 任务对象
     * @return 任务id
     */
    @Override
    public Long addTask(Task task) {
        Future<Long> future = threaPool.submit(new Callable<Long>() {
            @Override
            public Long call() throws Exception {
                // 添加任务到数据库
                boolean flag = addTaskToDB(task);
                if (flag) {
                    // 2,成功入库后添加到redis
                    addTaskToRedis(task);
                }
                return task.getTaskId(); // 返回任务信息表id
            }
        });
        try {
            return future.get();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    private void addTaskToRedis(Task task){
        // 使用任务类型_任务优先级拼接字符串做 key
        String key = task.getTaskType() + "_" + task.getPriority();
        // 计算未来时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        // 转换成毫秒值
        long timeInMillis = calendar.getTimeInMillis();
        // 小于当前时间就存入list队列
        if(task.getExecuteTime() <= System.currentTimeMillis()){
            String listKey = ScheduleConstants.TOPIC + key;
            redisCacheService.lLeftPush(listKey, JSON.toJSONString(task));
        }else if((task.getExecuteTime() > System.currentTimeMillis()) && (task.getExecuteTime()<= timeInMillis)){
            // 大于当前时间,小于未来5分钟的任务加入zadd
            redisCacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task),task.getExecuteTime());
        }
    }
    /**
     * 添加任务到数据库
     * @param task
     * @return
     */
    private boolean addTaskToDB(Task task) {
        boolean flag = false;
        try {
            // 1,添加到任务数据库
            //保存数据到任务表
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);
            // 向日志表添加数据
            Long taskId = taskinfo.getTaskId();
            task.setTaskId(taskId);
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);
            flag = true;
        } catch (BeansException e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 从redis拉取任务信息
     *
     * @param type
     * @param priority
     */
    @Override
    public Task poll(int type, int priority) {

        Future<Task> taskFuture = threadPoolTaskExecutor.submit(new Callable<Task>() {
            @Override
            public Task call() throws Exception {
                Task task = null;
                try {
                    String key = type+"_"+priority;
                    // congredis中获取数据
                    String rightPop = redisCacheService.lRightPop(ScheduleConstants.TOPIC + key);
                    task = JSON.parseObject(rightPop, Task.class);
                    if(task != null){
                        // 根据任务id从数据库中删除任务数据
                        taskinfoMapper.deleteById(task.getTaskId());
                        TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(task.getTaskId());
                        if (taskinfoLogs != null){
                            taskinfoLogs.setStatus(ScheduleConstants.EXECUTED);
                            taskinfoLogsMapper.updateById(taskinfoLogs);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return task;
            }
        });
        try {
            return taskFuture.get();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 定时任务
     */
    @Scheduled(cron = "0 */1 * * * ?") // 定时一分钟
    public void refresh(){
        threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                String token = redisCacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30); // 加锁
                if(StringUtils.isNotBlank(token)){
                    Set<String> futureScan = redisCacheService.scan(ScheduleConstants.FUTURE + "*");// future_*
                    if (futureScan != null && futureScan.size()>0){
                        for (String futureKey : futureScan) {
                            // 获取该key下的需要消费的任务数据
                            Set<String> score = redisCacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
                            if(!score.isEmpty()){
                                // 获取topic的键值key
                                String topicKey = ScheduleConstants.TOPIC + futureKey.substring(7);
                                // 存入消费队列,底层就是把set队列数据放到list消费队列中
                                redisCacheService.refreshWithPipeline(futureKey, topicKey,score);
                                System.out.println("成功的将" + futureKey + "下的当前需要执行的任务数据刷新到" + topicKey + "下");
                            }
                        }
                    }
                }
            }
        });
    }

    /**
     * 定时从数据库中拿数据到redis中
     */
    @PostConstruct
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadData(){
        // 删除缓存中未来数据集合和当前消费者队列的所有key
        Set<String> futurekeys = redisCacheService.scan(ScheduleConstants.FUTURE + "*");// future_
        Set<String> topickeys = redisCacheService.scan(ScheduleConstants.TOPIC + "*");// topic_
        redisCacheService.delete(futurekeys);
        redisCacheService.delete(topickeys);
        // 生成未来五分钟的时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        LambdaQueryWrapper<Taskinfo> queryWrapper = Wrappers.<Taskinfo>lambdaQuery().le(
                Taskinfo::getExecuteTime, calendar.getTime()
        );
        List<Taskinfo> taskinfoList = taskinfoMapper.selectList(queryWrapper);
        for (Taskinfo taskinfo : taskinfoList) {
            Task task = new Task();
            BeanUtils.copyProperties(taskinfo,task);
            task.setExecuteTime(taskinfo.getExecuteTime().getTime());
            addTaskToRedis(task);
        }
    }







}
